package com.example.movie.ui.cinema

import android.annotation.SuppressLint
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import cn.forward.androids.utils.ThreadUtil
import com.bumptech.glide.Glide
import com.example.movie.R
import com.example.movie.common.constants.AppConstants
import com.example.movie.common.entity.Plan
import com.example.movie.data.cinema.model.CinemaMovieItemInfo
import com.example.movie.data.cinema.model.vm.CinemaViewModel
import com.example.movie.data.movie.factory.CinemaViewModelFactory
import com.example.movie.ui.cinema.adapter.MoviePlanDateAdapter
import com.example.movie.ui.movie.adapter.PlanMovieListAdapter
import com.qmuiteam.qmui.widget.dialog.QMUITipDialog
import kotlinx.android.synthetic.main.fragment_movie_plan.*
import java.util.concurrent.TimeUnit

class MoviePlanActivity : AppCompatActivity() {

    private val cinemaViewModel: CinemaViewModel by viewModels(factoryProducer = { CinemaViewModelFactory() })

    private val idx2Mid = hashMapOf<Int, Int>()
    private val mid2Idx = hashMapOf<Int, Int>()

    private var hasSelectDefaultImage: Boolean = false
    private var loadImagesComplete: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.fragment_movie_plan)
        intent?.extras?.getInt("agentId")?.let {
            cinemaViewModel.loadPlanData(it)
        }
        initView()
    }

    @SuppressLint("SetTextI18n")
    private fun initView() {
        //加载排片轮播图
        cinemaViewModel.planMovieImages.observe(this, { it ->
            with(it.success) {
                this?.let {
                    repeat(it.size) { idx ->
                        with(it[idx]) {
                            //存储图片下标和图片id的双向对应关系
                            movieId?.let {
                                idx2Mid[idx] = movieId
                                mid2Idx[movieId] = idx
                            }
                        }
                    }

                    val images = mutableListOf<Bitmap>()
                    //异步加载图片数据
                    ThreadUtil.getInstance().execute() {
                        for (simpleMovieData in it) {
                            val img = Glide.with(this@MoviePlanActivity)
                                .asBitmap()
                                .load(AppConstants.STATIC_SOURCE_URL + simpleMovieData.movieImg)
                                .submit()
                                .get()
                            images.add(img)
                        }
                        picker.data = images
                        loadImagesComplete = true
                    }

                }
            }
        })

        //显示排片日期列表
        cinemaViewModel.planDates.observe(this, {
            with(it.success) {
                val planDates = mutableListOf<String>()
                this?.let { it ->
                    repeat(it.size) { idx ->
                        it[idx].apply {
                            planDates.add(this)
                        }
                    }
                    //日期从小到大排列
                    planDates.sort()
                    date_picker.layoutManager =
                        LinearLayoutManager(this@MoviePlanActivity, LinearLayoutManager.HORIZONTAL, false)
                    date_picker.adapter = MoviePlanDateAdapter(planDates, cinemaViewModel)
                    //选中第一个日期
                    cinemaViewModel.selectedPlanDay.value = planDates[0]
                }
            }
        })

        cinemaViewModel.defaultPlanVo.observe(this, { it ->
            it?.success?.apply {
                this.let {
                    if (it.isEmpty()) {
                        val dialog = QMUITipDialog.Builder(this@MoviePlanActivity).setTipWord("该影院暂无排片计划")
                            .setIconType(QMUITipDialog.Builder.ICON_TYPE_INFO)
                            .create()
                        dialog.show()

                        Handler(Looper.myLooper()!!).postDelayed({
                            dialog.dismiss()
                            onBackPressed()
                        }, TimeUnit.SECONDS.toMillis(2))

                        return@observe
                    }

                    selectDefaultImage(it[0])

                    val plans = mutableListOf<CinemaMovieItemInfo>()
                    repeat(it.size) { idx ->
                        with(it[idx]) {
                            plans.add(
                                CinemaMovieItemInfo(
                                    startTime,
                                    endTime,
                                    hallName,
                                    hallTypeName,
                                    seatPrice.toString(),
                                    planId
                                )
                            )
                            movie_name.text = movieName
                            movie_score.text = score.toString()
                            outline.text =
                                duration.toString() + "分钟 | " + movieTypeName + " | " + protagonist
                        }
                    }

                    with(LinearLayoutManager(this@MoviePlanActivity, LinearLayoutManager.VERTICAL, false)) {
                        movies.layoutManager = this
                        movies.adapter = PlanMovieListAdapter(plans,this@MoviePlanActivity)
                    }
                }
            }
        })

        picker.setOnSelectedListener { _, position ->
            cinemaViewModel.movieId.value = idx2Mid[position]
        }

        cinemaViewModel.movieId.observe(this, {
            cinemaViewModel.changeMovie()
        })

        cinemaViewModel.selectedPlanDay.observe(this, {
            cinemaViewModel.changePlanDate()
        })

    }

    /**
     * 当图片加载完成选中默认影片
     */
    private fun selectDefaultImage(p: Plan) {
        while (true) {
            if (hasSelectDefaultImage) {
                break
            } else if (mid2Idx[p.movieId] != null && loadImagesComplete) {
                hasSelectDefaultImage = true
                picker.selectedPosition = mid2Idx[p.movieId]!!
                //默认选中不会触发选择事件，因此要事先设置选中的movieId
                cinemaViewModel.movieId.value = idx2Mid[picker.selectedPosition]
            }
        }

    }

}